package com.lb.bs.client.util;

import com.lb.bs.client.constants.Constants;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

/**
 * program: LB-BS-Client
 * author: bsworld.xie
 * create: 2019-12-18 15:38
 * description:
 */
public class IPUtil {
    private static final int CONNECTION_TIMEOUT=2000;
    private static final int READ_TIMEOUT=500;

    public static String getLocalAddress() {
        try {
            byte[] bytes = InetAddress.getLocalHost().getHostAddress().getBytes();
            return new String(bytes);
        } catch (UnknownHostException var1) {
            return "";
        }
    }


    public static boolean isIPAddress(String ipHost) {
        if (StringUtils.isEmpty(ipHost)) {
            throw new IllegalStateException("ip 地址不合法");
        }
        try {
            String[] ips = ipHost.split(Constants.GRAY_SPLIT_SYMBOL);
            ipHost = ips[0];
            if (!ipHost.startsWith("http")) {
                ipHost = "http://" + ipHost;
            }
            URL url = new URL(ipHost);
            String host=url.getHost();
            InetAddress address = InetAddress.getByName(host);
            if(host.equalsIgnoreCase(address.getHostAddress())){
                return true;
            }
        } catch (MalformedURLException | UnknownHostException e) {
            throw new IllegalStateException("isIPAddress(), 解析失败,ipHost:" + ipHost);
        }
        return false;
    }



    public static String getUrlByHost(String url) {
        String result = "";
        BufferedReader in = null;
        if (url == null) return "";
        if (url.indexOf("http") < 0) {
            url = "http://" + url;
        }
        try {
            URLConnection connection = new URL(url).openConnection();
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.connect();
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            throw new IllegalStateException("ip 域名解析失败" + e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
            }
        }

        return result;
    }
}
